<template>
  <el-dialog
    :title="{ add: '新增角色', esit: '编辑角色' }[mode]"
    :visible="isShow"
    @close="cancelEvent"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="角色名字" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align:center">
        <el-button @click="cancelEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setting'
export default {
  props: {
    isShow: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      mode: 'add',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '必填', trigger: 'change' }],
        description: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  methods: {
    cancelEvent () {
      this.$emit('update:isShow', false)
      //  清空表单数据移除验证
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    //  分场景调用api
    submit () {
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            await sysRolePost(this.form)
            this.$message.success('新增角色成功!')
          } else if (this.mode === 'esit') {
            await sysRolePut(this.form)
            this.$message.success('编辑角色成功!')
          }
          this.cancelEvent()
          //  刷新父级列表数据
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style></style>
